﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using 沙鹿便签.Binding;

namespace 沙鹿便签.Model
{
    class TaskStorageUtil
    {
        public static ObservableCollection<CTask> LoadTask(string filename)
        {
            return null;
        }
        public static void SaveTask(TaskCollection tasks, string filename)
        {
            using (IsolatedStorageFile userstorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (userstorage.FileExists(filename))
                {
                    userstorage.CopyFile(filename, filename + ".bak");
                    userstorage.DeleteFile(filename);           
                }
                using (FileStream fs = userstorage.CreateFile(filename))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<CTask>));
                    try
                    {
                        xs.Serialize(fs, tasks.Items);
                        if (userstorage.FileExists(filename + ".bak"))
                        {
                            userstorage.DeleteFile(filename + ".bak");
                        }
                    }
                    catch (Exception arg)
                    {
                        Debug.WriteLine(arg.Message);
                        if (userstorage.FileExists(filename + ".bak"))
                        {
                            userstorage.CopyFile(filename + ".bak", filename);
                            userstorage.DeleteFile(filename + ".bak");
                        }
                        
                    }
                    

                }
                
            }
            
        }
        public static void DeleteTask(string filename)
        { 
            using(IsolatedStorageFile userstorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (userstorage.FileExists(filename))
                {
                    userstorage.DeleteFile(filename);
                }
            }
        }
       
    }
}
